﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using WP7Contrib.View.Controls.Extensions;
using MetroInMotionUtils;
using WP7Contrib.View.Controls;

namespace SandwichFlow
{
  public partial class KeywordPage : PhoneApplicationPage
  {
    private ItemFlyInAndOutAnimations _flyOutAnimation = new ItemFlyInAndOutAnimations();

    public KeywordPage()
    {
      this.Loaded += new RoutedEventHandler(Page_Loaded);

      InitializeComponent();
    }

    private void Page_Loaded(object sender, RoutedEventArgs e)
    {
      Dispatcher.BeginInvoke(() => _flyOutAnimation.ItemFlyIn());
    }

    protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
    {
      base.OnNavigatedTo(e);

      // parse the querystring to extract the id
      long id = long.Parse(NavigationContext.QueryString["id"]);

      // obtain this item from the view model.
      SandwichFlowViewModel viewModel = ((App)Application.Current).RootFrame.DataContext as SandwichFlowViewModel;
      this.DataContext = viewModel.Keywords.Where(s => s.Id == id).Single();
   
    }

    private void NavigationList_Navigation(object sender, NavigationListEventArgs e)
    {
      var selectedItem = e.Item as Sandwich;

      // grab the Title element
      var exitAnimationElement = sandwichList.Descendants()
                                        .OfType<TextBlock>()
                                        .Where(el => el.DataContext == selectedItem)
                                        .Where(el => el.Name == "Title")
                                        .Single();

      if (exitAnimationElement != null)
      {
        // animate the element, navigating to the new page when the animation finishes
        _flyOutAnimation.ItemFlyOut(this, exitAnimationElement, () =>
        {
          NavigationService.Navigate(new Uri("/SandwichRecipe.xaml?id=" +
            selectedItem.Id.ToString(), UriKind.Relative));
        });
      } 
    }

  }
}